package com.caishi.lkx.user.service.impl;

import cn.hutool.core.util.ObjectUtil;

import com.caishi.lkx.common.CommonResultCode;
import com.caishi.lkx.user.mapper.SysDictTypeMapper;
import com.caishi.lkx.user.model.SysDictTypeModel;
import com.caishi.lkx.user.service.ISysDictDetailService;
import com.caishi.lkx.user.service.ISysDictTypeService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.IBaseMapper;
import com.zzw.common.exception.BizRuntimeException;
import com.zzw.common.service.NameService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @Param:
 * @return
 * @Author: huangpeng
 * @Date: 2021/9/23 9:37
 * @Description:
 */
@Service
public class SysDictTypeServiceImpl implements ISysDictTypeService, NameService<SysDictTypeModel,String> {

    @Resource
    private SysDictTypeMapper sysDictTypeMapper;
    @Resource
    private ISysDictDetailService sysDictDetailService;

    @Override
    public IBaseMapper<SysDictTypeModel, String> getMapper() {
        return sysDictTypeMapper;
    }

    @Override
    public SysDictTypeModel insert(SysDictTypeModel entity) {
        SysDictTypeModel model = this.selectOne(Wrappers.<SysDictTypeModel>lambdaQuery()
                .select(SysDictTypeModel::getId)
                .eq(SysDictTypeModel::getCode, entity.getCode()));
        if (null != model) {
            throw new BizRuntimeException("编码已存在");
        }
        getMapper().insert(entity);
        return entity;
    }

    @Override
    public SysDictTypeModel simpleUpdate(SysDictTypeModel entity) {
        if (ObjectUtil.isEmpty(entity.getId())) {
            throw new BizRuntimeException("update必须拥有Id", CommonResultCode.dataChangeError.getCode());
        }

        SysDictTypeModel model = this.selectOne(Wrappers.<SysDictTypeModel>lambdaQuery()
                .select(SysDictTypeModel::getId)
                .eq(SysDictTypeModel::getCode, entity.getCode()));
        if (null != model && !entity.getId().equals(model.getId())) {
            throw new BizRuntimeException("编码已存在");
        }
        return getMapper().updateById(entity) == 1 ? entity : null;
    }

    @Override
    public SysDictTypeModel getByCode(String areaCode) {
        return  this.selectFirst(Wrappers.<SysDictTypeModel>lambdaQuery().eq(SysDictTypeModel::getCode,areaCode));
    }

}
